package com.sjm.suchbear.easymap;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sjm.suchbear.easymap.Model.TraceModel;
import com.sjm.suchbear.easymap.Model.UpImageModel;
import com.sjm.suchbear.easymap.Model.UploadModel;
import com.sjm.suchbear.easymap.Service.iHttpService;
import com.sjm.suchbear.easymap.Util.DialogLoading;
import com.sjm.suchbear.easymap.Util.GifSizeFilter;
import com.sjm.suchbear.easymap.Util.HttpUtils;
import com.sjm.suchbear.easymap.View.MyGridView;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;
import zilla.libcore.util.Util;

public class HistoryDetilActivity extends AppCompatActivity {

    @BindView(R.id.ll_header_back)
    LinearLayout llHeaderBack;
    @BindView(R.id.tv_list_title)
    TextView tvListTitle;
    @BindView(R.id.iv_header_function_ico)
    ImageView ivHeaderFunctionIco;
    @BindView(R.id.ll_header_function)
    LinearLayout llHeaderFunction;
    @BindView(R.id.ll_List_Main)
    RelativeLayout llListMain;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.iv_addPic)
    ImageView ivAddPic;
    @BindView(R.id.gv_pic)
    MyGridView gvPic;
    @BindView(R.id.iv_addVedio)
    ImageView ivAddVedio;
    @BindView(R.id.iv_showSmallVedio)
    ImageView ivShowSmallVedio;
    @BindView(R.id.tv_post)
    TextView tvPost;
    @BindView(R.id.iv_SmallVedio)
    ImageView ivSmallVedio;
    @BindView(R.id.sv_addFeed)
    ScrollView svAddFeed;
    @BindView(R.id.tv_showContent)
    TextView tvShowContent;
    @BindView(R.id.gv_showpic)
    MyGridView gvShowpic;
    @BindView(R.id.ll_showPic)
    LinearLayout llShowPic;
    @BindView(R.id.ll_showVedio)
    LinearLayout llShowVedio;
    @BindView(R.id.sv_showFeed)
    ScrollView svShowFeed;
    @BindView(R.id.iv_bo)
    ImageView ivBo;

    private int showmode;   //0:添加反馈 1:展示反馈
    private String patrolId;
    private List<Uri> mSelected;
    private static int REQUEST_IMAGE_CODE_CHOOSE = 0x111;
    private static int REQUEST_VEDIO_CODE_CHOOSE = 0x222;
    private static int RESULT_REQUEST_CODE = 0x333;
    private iHttpService service;
    private TraceModel mTracemodel;
    private List<UpImageModel> upImageList = new ArrayList<>();
    private String[] from = {"image", "text"};
    private int[] to = {R.id.image, R.id.text};
    private SimpleAdapter simpleAdapter;
    private List<Bitmap> icon = new ArrayList<>();
    private List<String> iconName = new ArrayList<>();
    private List<Map<String, Object>> data_list = new ArrayList<>();
    private String vedioPath = "";
    private int totalNum = 0;
    private int handleNum = 0;
    private static int NEWRESULT = 0x011;
    private static int OLDRESULT = 0x022;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history_detil);
        ButterKnife.bind(this);
        service = HttpUtils.createService(this);
        showmode = getIntent().getIntExtra("showmode", 0);
        patrolId = getIntent().getStringExtra("patrolId");
        initView();
    }

    private void initView() {
        switch (showmode) {
            case 0:
                tvListTitle.setText("添加反馈");
                svAddFeed.setVisibility(View.VISIBLE);
                svShowFeed.setVisibility(View.GONE);
                simpleAdapter = new SimpleAdapter(this, data_list, R.layout.item_simple, from, to);
                simpleAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
                                                @Override
                                                public boolean setViewValue(View view, Object data, String textRepresentation) {
                                                    if (view instanceof ImageView && data instanceof Bitmap) {
                                                        ImageView i = (ImageView) view;
                                                        i.setImageBitmap((Bitmap) data);
                                                        return true;
                                                    }
                                                    return false;
                                                }
                                            }
                );
                gvPic.setAdapter(simpleAdapter);
                break;
            case 1:
                tvListTitle.setText("反馈详情");
                svAddFeed.setVisibility(View.GONE);
                svShowFeed.setVisibility(View.VISIBLE);
                simpleAdapter = new SimpleAdapter(this, data_list, R.layout.item_simple, from, to);
                simpleAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
                                                @Override
                                                public boolean setViewValue(View view, Object data, String textRepresentation) {
                                                    if (view instanceof ImageView && data instanceof Bitmap) {
                                                        ImageView i = (ImageView) view;
                                                        i.setImageBitmap((Bitmap) data);
                                                        return true;
                                                    }
                                                    return false;
                                                }
                                            }
                );
                gvShowpic.setAdapter(simpleAdapter);
                getPatrolInfo();
                break;
        }
    }

    @OnClick({R.id.ll_header_back, R.id.iv_addPic, R.id.iv_addVedio, R.id.tv_post})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_header_back:
                finish();
                break;
            case R.id.iv_addPic:
                showImageChoose();
                break;
            case R.id.iv_addVedio:
                showVedioChoose();
                break;
            case R.id.tv_post:
                gettotalNum();
                if (totalNum == 0) {
                    Util.toastMsg("什么也没有上传");
                    return;
                } else {
                    setResult(NEWRESULT);
                }
                if (!String.valueOf(etContent.getText()).trim().equals("")) {
                    uploadComments(String.valueOf(etContent.getText()).trim());
                }
                if (upImageList.size() > 0) {
                    for (int i = 0; i < upImageList.size(); i++) {
                        uploadPic(upImageList.get(i).getImageBit(), upImageList.get(i).getImageName());
                    }
                }
                if (!vedioPath.equals("")) {
                    File file = new File(vedioPath);
                    Map<String, RequestBody> map = new HashMap<>();
                    String fileName = GetRandomName().concat(vedioPath.substring(vedioPath.indexOf(".")));
                    map.put("fileType", parseRequestBody("vedio"));
                    map.put("fileName", parseRequestBody(fileName));
                    map.put("patrolId", parseRequestBody(patrolId));
                    map.put(parseFileMapKey("file", fileName), parseFileRequestBody(file));
                    uploadMedia(map);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_CODE_CHOOSE && resultCode == RESULT_OK) {  //处理返回图片
            mSelected = Matisse.obtainResult(data);
            if (mSelected.size() + upImageList.size() == 5) {
                ivAddPic.setVisibility(View.GONE);
            }
            Log.d("Matisse", "mSelected: " + mSelected);
            for (int i = 0; i < mSelected.size(); i++) {
                Bitmap photo = GetBitmap(getRealPathFromURI(this, mSelected.get(i)), getColumn(), getColumn());
                icon.add(photo);
                iconName.add("");
                getData();
                simpleAdapter.notifyDataSetChanged();
                String realPath = getRealPathFromURI(this, mSelected.get(i));
                UpImageModel upImageModel = new UpImageModel();
                upImageModel.setImageBit(bitmapToBase64(GetRealBitmap(realPath)));
                upImageModel.setImageName(GetRandomName() + realPath.substring(realPath.indexOf(".")));
                upImageList.add(upImageModel);
            }
        }
        if (requestCode == REQUEST_VEDIO_CODE_CHOOSE && resultCode == RESULT_OK) {  //处理返回视频
            mSelected = Matisse.obtainResult(data);
            vedioPath = getRealPathFromURI(getBaseContext(), mSelected.get(0));
            ivSmallVedio.setVisibility(View.VISIBLE);
            ivSmallVedio.setImageBitmap(getVedioPic(mSelected.get(0)));
            ivBo.setVisibility(View.VISIBLE);
            ivAddVedio.setVisibility(View.GONE);
            Log.d("Matisse", "mSelected: " + mSelected);
        }
    }

    private void getPatrolInfo() {
        service.getPatrolInfo(patrolId)
                .subscribeOn(Schedulers.io())//指定网络请求在IO线程
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        DialogLoading.StartLodingDialog(HistoryDetilActivity.this);
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())//显示Dialog在主线程中
                .observeOn(AndroidSchedulers.mainThread())//显示数据在主线程
                .subscribe(new Subscriber<TraceModel>() {
                    @Override
                    public void onCompleted() {
                        DialogLoading.StopLodingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        DialogLoading.StopLodingDialog();
                        Util.toastMsg("网络连接失败");
                    }

                    @Override
                    public void onNext(TraceModel traceModel) {
                        mTracemodel = traceModel;
                        //初始化内容 图片 视频
                        if (traceModel.getContent() != null) {
                            tvShowContent.setText(traceModel.getContent());
                        }
                        if (traceModel.getImglist().size() > 0) {
                            icon.clear();
                            iconName.clear();
                            DialogLoading.StartLodingDialog(HistoryDetilActivity.this);
                            GetPic getPic = new GetPic(traceModel.getImglist());
                            getPic.start();
                        }
                        if (!traceModel.getVediourl().equals("")) {
                            ivShowSmallVedio.setVisibility(View.VISIBLE);
                            ivBo.setVisibility(View.VISIBLE);
                            ivBo.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Uri uri = Uri.parse(mTracemodel.getVediourl());
                                    Intent intent = new Intent(Intent.ACTION_VIEW);
                                    intent.setDataAndType(uri, "video/mp4");
                                    startActivity(intent);
                                }
                            });
                        }
                    }
                });
    }

    private void uploadComments(String comment) {
        service.uploadComments("comments", comment, patrolId)
                .subscribeOn(Schedulers.io())//指定网络请求在IO线程
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        DialogLoading.StartLodingDialog(HistoryDetilActivity.this);
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())//显示Dialog在主线程中
                .observeOn(AndroidSchedulers.mainThread())//显示数据在主线程
                .subscribe(new Subscriber<UploadModel>() {
                    @Override
                    public void onCompleted() {
                        handleNum++;
                        if (totalNum == handleNum) {
                            DialogLoading.StopLodingDialog();
                            showmode = 1;
                            initView();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        handleNum++;
                        if (totalNum == handleNum) {
                            DialogLoading.StopLodingDialog();
                            showmode = 1;
                            initView();
                        }
                        Util.toastMsg("评论上传错误");
                    }

                    @Override
                    public void onNext(UploadModel uploadModel) {
                        //成功或失败
                        if (uploadModel.getUpload().equals("success")) {
                            Util.toastMsg("文本反馈上传成功");
                        } else {
                            Util.toastMsg(uploadModel.getUpload());
                        }
                    }
                });
    }

    private void uploadPic(String mbitmap, String imgName) {
        service.uploadPic("image", mbitmap, imgName, patrolId)
                .subscribeOn(Schedulers.io())//指定网络请求在IO线程
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        DialogLoading.StartLodingDialog(HistoryDetilActivity.this);
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())//显示Dialog在主线程中
                .observeOn(AndroidSchedulers.mainThread())//显示数据在主线程
                .subscribe(new Subscriber<UploadModel>() {
                    @Override
                    public void onCompleted() {
                        handleNum++;
                        if (totalNum == handleNum) {
                            DialogLoading.StopLodingDialog();
                            showmode = 1;
                            initView();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        handleNum++;
                        if (totalNum == handleNum) {
                            DialogLoading.StopLodingDialog();
                            showmode = 1;
                            initView();
                        }
                        Util.toastMsg("图片上传失败");
                    }

                    @Override
                    public void onNext(UploadModel uploadModel) {
                        //成功或失败
                        if (uploadModel.getUpload().equals("success")) {
                            Util.toastMsg("图片上传成功");
                        } else {
                            Util.toastMsg(uploadModel.getUpload());
                        }
                    }
                });
    }


    private void uploadMedia(Map<String, RequestBody> map) {
        service.uploadMedia(map)
                .subscribeOn(Schedulers.io())//指定网络请求在IO线程
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        DialogLoading.StartLodingDialog(HistoryDetilActivity.this);
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())//显示Dialog在主线程中
                .observeOn(AndroidSchedulers.mainThread())//显示数据在主线程
                .subscribe(new Subscriber<UploadModel>() {
                    @Override
                    public void onCompleted() {
                        handleNum++;
                        if (totalNum == handleNum) {
                            DialogLoading.StopLodingDialog();
                            showmode = 1;
                            initView();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("HistoryDetilActivity", e.getMessage());
                        handleNum++;
                        if (totalNum == handleNum) {
                            DialogLoading.StopLodingDialog();
                            showmode = 1;
                            initView();
                        }
                        Util.toastMsg("网络连接失败");
                    }

                    @Override
                    public void onNext(UploadModel uploadModel) {
                        //成功或失败
                        if (uploadModel.getUpload().equals("success")) {
                            Util.toastMsg("视频上传成功");
                        } else {
                            Util.toastMsg(uploadModel.getUpload());
                        }
                    }
                });
    }

    private class GetPic extends Thread {
        private List<TraceModel.ImglistBean> mimglist;

        public GetPic(List<TraceModel.ImglistBean> mimglist) {
            this.mimglist = mimglist;
        }

        @Override
        public void run() {
            super.run();
            for (int i = 0; i < mimglist.size(); i++) {
                if (!mimglist.get(i).getImgurl().equals("")) {
                    try {
                        String url = mimglist.get(i).getImgurl();
                        Bitmap bitmap = Glide.with(getApplicationContext())
                                .load(url)
                                .asBitmap()
                                .centerCrop()
                                .into(getColumn(), getColumn())
                                .get();
                        icon.add(bitmap);
                        iconName.add("");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }
            }
            Message msg = new Message();
            msg.what = 0x111;
            mHandler.sendEmptyMessage(0x111);
        }
    }

    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0x111) {
                getData();
                try {
                    simpleAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    Log.e("HistoryDetilActivity", String.valueOf(e));
                }
                DialogLoading.StopLodingDialog();
            }
            return true;
        }
    });


    private void showVedioChoose() {
        Matisse.from(HistoryDetilActivity.this)
                .choose(MimeType.ofVideo())
                .countable(true)
                .maxSelectable(1)
                .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .captureStrategy(
                        new CaptureStrategy(true, "com.suchbear.EasyMap.fileprovider"))
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .theme(R.style.Matisse_Dracula)
                .forResult(REQUEST_VEDIO_CODE_CHOOSE);
    }

    private void showImageChoose() {
        Matisse.from(HistoryDetilActivity.this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(5 - upImageList.size())
                .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .captureStrategy(
                        new CaptureStrategy(true, "com.suchbear.EasyMap.fileprovider"))
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .theme(R.style.Matisse_Dracula)
                .forResult(REQUEST_IMAGE_CODE_CHOOSE);
    }

    private List<Map<String, Object>> getData() {
        data_list.removeAll(data_list);
        //cion和iconName的长度是相同的，这里任选其一都可以
        for (int i = 0; i < icon.size(); i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("image", icon.get(i));
            map.put("text", iconName.get(i));
            data_list.add(map);
        }
        return data_list;
    }


    private Bitmap getVedioPic(Uri uri) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(getBaseContext(), uri);
        Bitmap bmp = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        Bitmap mBitmap = Bitmap.createScaledBitmap(bmp, 200, 200, true);
        return mBitmap;
    }

    private String GetRandomName() {
        String backstr = "";
        for (int i = 0; i < 8; i++) {
            Random ra = new Random();
            String tempstr = String.valueOf(ra.nextInt(10));
            backstr = backstr + tempstr;
        }
        return backstr;
    }

    /**
     * bitmap转为base64
     *
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    public static String getRealPathFromURI(Context mContext, Uri contentUri) {

        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = mContext.getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }

    //通过路径将图片转化为Bitmap
    public static Bitmap GetBitmap(String path, int w, int h) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
        BitmapFactory.decodeFile(path, opts);
        int width = opts.outWidth;
        int height = opts.outHeight;
        float scaleWidth = 0.f, scaleHeight = 0.f;
        if (width > w || height > h) {
            scaleWidth = ((float) width) / w;
            scaleHeight = ((float) height) / h;
        }
        opts.inJustDecodeBounds = false;
        float scale = Math.max(scaleWidth, scaleHeight);
        opts.inSampleSize = (int) scale;
        WeakReference<Bitmap> weak = new WeakReference<Bitmap>(
                BitmapFactory.decodeFile(path, opts));
        return Bitmap.createScaledBitmap(weak.get(), w, h, true);
    }

    public static Bitmap GetRealBitmap(String path) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
        BitmapFactory.decodeFile(path, opts);
        int width = opts.outWidth;
        int height = opts.outHeight;
        opts.inJustDecodeBounds = false;
        float scale = 1;
        opts.inSampleSize = (int) scale;
        WeakReference<Bitmap> weak = new WeakReference<Bitmap>(
                BitmapFactory.decodeFile(path, opts));
        return Bitmap.createScaledBitmap(weak.get(), width, height, true);
    }

    private int getColumn() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int w_screen = dm.widthPixels;
        int columnWidth = (w_screen - 40 - 27) / 3;
        return columnWidth;
    }

    public static RequestBody parseRequestBody(String value) {
        return RequestBody.create(MediaType.parse("text/plain"), value);
    }

    public static RequestBody parseFileRequestBody(File file) {
        return RequestBody.create(MediaType.parse("multipart/form-data"), file);
    }

    public static String parseFileMapKey(String key, String fileName) {
        return key + "\"; filename=\"" + fileName;
    }

    private boolean getDialogState(int type) {
        switch (type) {
            case 1:
                if (upImageList.size() > 0) {
                    return false;
                }
                if (!vedioPath.equals("")) {
                    return false;
                }
                break;
            case 2:
                if (!vedioPath.equals("")) {
                    return false;
                }
                break;
            case 3:
                break;
        }
        return true;
    }

    private void gettotalNum() {
        if (!String.valueOf(etContent.getText()).trim().equals("")) {
            totalNum++;
        }
        if (upImageList.size() > 0) {
            totalNum = totalNum + upImageList.size();
        }
        if (!vedioPath.equals("")) {
            totalNum++;
        }
    }

}
